﻿using UnityEngine;
using System.Collections;
using ProtoBuf.Message;

//namespace Net
//{
public class NetAPI
{

    private static NetWork.Layer.HTTPManager http;
    private static NetWork.SocketController _socket;
    private static string mainName = "Main";

    private static NetWork.SocketController socket
    {
        get
        {
            if (_socket == null)
            {
                _socket = new NetWork.SocketController(mainName);
                NetWork.NetTickCtrl.Instance.InsertSocket(_socket);
            }
            return _socket;
        }
    }
    private static int currSceneId = (int)NetWork.ServerType.town;

    public static int CurrSceneId
    {
        get
        {
            //return (int)NetWork.ServerType.town;
            return currSceneId; 
        }
        set
        {
            currSceneId = value;
        }
    }

    #region http
    public static void InitHttp(string url)
    {
        http = NetWork.Layer.HTTPManager.Init(url, mainName);
        NetWork.NetTickCtrl.Instance.InsertHttp(http);
    }

    public static void ResetHttpServerUrl(string url)
    {
        http.SetServerUrl(url);
    }

    public static void ReconnectHttp(string url)
    {
        http.ReconnectServer(url);
    }

    public static bool SendHttp(int opcode, object pbData, NetWork.Layer.HttpHandler handler)
    {
        return http.Send(opcode, pbData, handler);
    }
    
    public static void SendHttpInBackground(int opcode, object pbData, NetWork.Layer.HttpHandler handler)
    {
        NetWork.Layer.WWWHttpUtil.Instance.Send(opcode, pbData, handler);
    }


    public static bool IsSendingHttp()
    {
        return http.isSending();
    }

    public static bool HttpResendTimeOut()
    {
        return http.ResendTimeOut();
    }
    #endregion

    #region socket

    public static void ConnectSocket(string ip, int host)
    {
        socket.Connect(ip, host, SendSocketLogin);
    }

    /*
    public static void SendSocket (int opcode, object pbData, NetWork.ServerType type)
    {
        socket.Send (opcode, pbData, type);
    }
    */
    public static void SendSocket(int opcode, object pbData)
    {
        socket.Send(opcode, pbData);
    }


    public static void RegistSocketHandler(int nMsgId, NetWork.Sockets.Event.Msg.DelegateFunc Handler)
    {
        socket.RegisterMsgListener(nMsgId, Handler);
    }

    public static void UnregisterSocketHandler(int nMsgId, NetWork.Sockets.Event.Msg.DelegateFunc Handler)
    {
        socket.UnregisterMsgListener(nMsgId, Handler);
    }

    public static bool SocketIsConnected()
    {
        if (socket != null && socket.IsConnected())
        {
            return true;
        }
        return false;
    }

    public static void Disconnect()
    {
        if(socket != null)
        {
            socket.Disconnect();
        }
    }

    public static void Reconnect()
    {
        BoxManager.ClearSocketBox();
        CSRefreshGatewayIPAndPort rgpp = new CSRefreshGatewayIPAndPort();
        rgpp.sessionKey = StaticData.sessionKey;
        SendHttpInBackground(OpDefine.CSRefreshGatewayIPAndPort, rgpp, RefreshSocketAddress);
    }

    public static void RefreshSocketAddress(NetWork.Packets.Packet packet,bool success)
    {
        if(success)
        {
            SCRefreshGatewayIPAndPort rgip = (SCRefreshGatewayIPAndPort)packet.kBody;
            StaticData.socketIp = rgip.ip;
            StaticData.socketPort = rgip.port;
        }
        socket.ReConnect(SendSocketLogin);
    }

    public static void SendSocketLogin(int connRet)
    {
        Debug.Log("ConnectCallback() ret = " + connRet);
        if (connRet == 0)
        {
            RegistSocketHandler(OpDefine.SCSocketLogin, SCLoginTcpCallback);
            CSSocketLogin msg = new CSSocketLogin();
            msg.sessionKey = StaticData.sessionKey;
            SendSocket(OpDefine.CSSocketLogin, msg);
            Debug.Log("[Reconnect] SendCSLogin:");
        }
        //else
        //{
        //    ShowNeedSocketConnect(); 
        //}
    }

    public static void SCLoginTcpCallback(object obj)
    {
        NetAPI.UnregisterSocketHandler(OpDefine.SCSocketLogin, SCLoginTcpCallback);
        SCSocketLogin msg = (SCSocketLogin)obj;
        Debug.Log("[Reconnect] SCLoginTcpCallback:");
        Debug.Log("result = " + msg.result);
       
        if (msg.result == 100)
        { //登录成功
            StaticData.netBreak = false;
            DataMessageTool.AddMessage(DataMessage.NET_CONNECT_COMPLETE, socket);
        }
        else
        {
            Debug.LogError("connect error " + msg.result);
        }
    }

    #endregion

    #region Tools

    public static void CloseHttp()
    {
        if(http != null)
        {
            http.CleanCatch();
            NetWork.NetTickCtrl.Instance.RemoveHttp(http.Name);
            http = null;
        }
    }

    public static void CloseSocket()
    {
        if(socket != null)
        {
            NetWork.NetTickCtrl.Instance.RemoveSocket(_socket.Name);
            _socket = null;
        }
    }
    #endregion

    #region UI about

    public static void CleanNetBox()
    {
        BoxManager.ClearNetMask();
    }

    public static void ShowNetWaitBox()
    {
        BoxManager.CreateNetMask();
    }

    public static void ShowNetTimeOutBox()
    {
        BoxManager.CreateNetTimeOut(
            delegate
            {
                CleanNetBox();
                HttpResendTimeOut();
            }
        );
    }

    public static void ShowNetErrorBox(string error)
    {
        BoxManager.CreateNetError(error);
    }

    public static void ShowNeedSocketConnect(bool isError = false)
    {
        //打开充值界面的时候不弹网络断开
        if(UI.PageManager.Instance!=null)
        {
            if(UI.PageManager.Instance.currentPage!=null)
            {
                if (UI.PageManager.Instance.currentPage.name.Equals("ChargePage"))
                    return;
            }
        }
        BoxManager.CreateSocketReconnect(isError ? LanguageTool.GetTextNoUpdate(1031): LanguageTool.GetTextNoUpdate(1030), Reconnect);
    }


    #endregion

}
